#include <stdio.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <cctype>

#include "GenerateOpusFile.h"
#include "PlayOpus.h"
#include "ConvertToOpus.h"
#include "PlayWav.h"

void PlayAudio(const char *audio_file);
void ShowHelper(const char *program_name);

std::string toLower(const std::string& str) 
{
    std::string result = str;
    std::transform(result.begin(), result.end(), result.begin(), 
                   [](unsigned char c) { return std::tolower(c); });
    return result;
}

int main(int argc,char *argv[])
{
    for (int i = 0; i < argc; i++)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }

    if ((argc == 4) && (strncmp(argv[1], "record", sizeof("record")) == 0))
    {
        RecordAudio(argv[2], atoi(argv[3]));
        return 0;
    }
    // 播放Opus文件功能
    else if (argc == 3)
    {
        if(strncmp(argv[1], "generate", sizeof("generate")) == 0)
        {
            char output_file[128] = {0};
            strncpy(output_file, argv[1], sizeof(output_file));
            generateSinOpus(output_file);
            return 0;
        }
        else if (argc == 3) 
        {
            ConvertWavToOpus(argv[1], argv[2]);
            return 0;
        }
    }
    else if (argc == 2) 
    {
        PlayAudio(argv[1]);
        return 0;
    }

    ShowHelper(argv[0]);

    
    return 0;
}

void PlayAudio(const char *audio_file)
{
    std::string audio_file_str(audio_file);
    std::string strSuffix = audio_file_str.substr(audio_file_str.find_last_of(".") + 1);
    printf("audio_file: %s, suffix: %s\n", audio_file, strSuffix.c_str());

    strSuffix = toLower(strSuffix);
    
    if (strSuffix == "opus")       // opus
    {
        PlayOpusFile(audio_file);
    }
    else if (strSuffix == "wav")   // wav
    {
        PlayWavFile(audio_file);
    }
}

void ShowHelper(const char *program_name)
{
    printf("Usage: %s record record.wav 10\n", program_name); 
    printf("Usage: %s xxx.wav xxx.opus \n", program_name); 
    printf("Usage: %s generate SIN1KHzopus.opus \n", program_name);
    printf("Usage: %s play <audio_file> : paly audio file \n", program_name);

    return;
}